<!--
 * @Description: 附件、关联文档展示
-->
<template>
  <div :class="['accessory-item-container', { 'accessory-item': isHorizontalMode }]">
    <div :class="{ 'summary-container': isShowBatchDownload }">
      <i :class="['syIcon', isDoc ? 'sy-associated_document' : 'sy-attachment', { 'color-primary': !isNewMode }]"></i>
      <span class="data-length">({{ dataLength }})</span>
      <a-tooltip v-if="isShowBatchDownload && !isDoc" :title="$i18n('doc.menu.downloadFile.label')">
        <a class="batch-download" :href="batchDownloadUrl">
          <icon-font type="sy-batch-download" />
        </a>
      </a-tooltip>
    </div>
    <ul :class="{ 'list-container': isHorizontalMode || isDoc }">
      <li
        v-for="(item, index) in dataList"
        :key="item.fileUrl"
        :class="{ 'item-wrapper': isNewMode }"
      >
        <section class="left-item">
          <span
            v-if="item.type !== 1"
            :class="createFileIconString(item)"
          >
          </span>
          <a-tooltip :title="item.filename">
            <NameElement :file="item" class="name" />
          </a-tooltip>
          <span v-if="isNewMode && !isDoc" class="file-size">({{ getFileSize(item.size) }})</span>
        </section>
        <section class="right-item">
          <template v-if="hasDelete || item.isUploading">
            <icon-font
              v-if="isNewMode"
              type="sy-delete-x"
              :title="$i18n('link.jsp.del')"
              class="delete-icon"
              @click="deleteItem(item, index)"
            />
            <span
              v-else
              class="ico16 affix_del_16"
              :title="$i18n('link.jsp.del')"
              @click="deleteItem(item, index)"
            >
            </span>
          </template>
          <div
            v-if="item.isUploading"
            class="progress-bg"
            :style="`width:${item.process}%`"
          >
          </div>
          <FileHandleList
            :file="item"
            v-if="isShowHandle"
            :isNewMode="isNewMode"
          />
        </section>
      </li>
    </ul>
  </div>
</template>
<script>
  /* global fileUploadAttachments */

  import FileHandleList from './components/handle';
  import NameElement from './components/name-element';
  //引入回显关联文档对象操作
  import { addDataList, createID, createAttachment } from '@/helper/relation-doc';
  import globalData from '@/plugins/data';
  import globalMethods from '@/plugins/methods';
  import {useBaseInfoWithOut} from "@/store/modules/base-info";
  const useBaseInfo = useBaseInfoWithOut();
  export default {
    name: 'AccessoryItem',
    components: {
      FileHandleList,
      NameElement,
    },
    props: {
      //传递的数据列表
      dataList: { type: Array },
      //是否是关联文档
      isDoc: {
        type: Boolean,
        default: false,
      },
      //关联文档区域名称,用于关联文档选择数据回显
      areaName: { type: String, default: 'doc1' },
      //是否有删除按钮
      hasDelete: {
        type: Boolean,
        default: false,
      },
      isNewMode: { // 是否为新组件模式
        type: Boolean,
        default: false,
      },
      isShowBatchDownload: { // 是否显示批量下载
        type: Boolean,
        default: false,
      },
      layout: { // 排列方式
        type: String,
        default: 'horizontal',
        validator: value => ['horizontal', 'vertical'].includes(value),
      },
    },
    computed: {
      dataLength() {
        return this.dataList.length > 99 ? '99+' : this.dataList.length;
      },
      //是否移上去展示操作框
      isShowHandle() {
        // !this.hasDelete && !this.isShowImg && !onlineEdit && this.type !== 2    type:2 是关联文档
        return !this.isDoc && !this.hasDelete;
      },
      // 批量下载附件
      batchDownloadUrl() {
        const fileIds = this.dataList.map(({ fileUrl }) => fileUrl);
        const zipFileName = globalMethods.getDateString(Date.now(), 'YYYY-MM-DD/HH-mm-ss');
        const url = `${globalData.ctxPath}/rest/attachment/file/batchDownload/${fileIds.join(',')}?zipFileName=${encodeURIComponent(zipFileName)}`;

        return url;
      },
      // 横排排列模式
      isHorizontalMode() {
        return this.layout === 'horizontal';
      },
      attachmentReady() {
        return this.dataList.map(item => item.process);
      }
    },
    watch: {
      attachmentReady(val) {
        let some = this.dataList.some(item => item.isUploading === true && item.process !== 100);
        if (some) {
          if (!useBaseInfo.attachmentUploading) {
            useBaseInfo.attachmentUploading = true;
            console.log('附件正在上传', val);
          }
        } else {
          useBaseInfo.attachmentUploading = false;
          console.log('附件正上传完成', val);
        }
      },
    },
    mounted() {
      //如果是关联文档，那么就填入全局对象，以便再选文档的时候回显
      if (this.isDoc && this.dataList.length) {
        addDataList(createAttachment(this.dataList, this.areaName), this.areaName);
      }
    },
    methods: {
      /**
       * @description: 生成文件图标
       * @param {Object} item 当前文件对象
       * @return {String}返回图标类名
       */
      createFileIconString(item) {
        // 致信的做特殊判断
        if (item.mimeType === 'uc') {
          return 'syDoc zhi_chat';
        }
        // 关联文档用老图标。修改附件的回来没有iconFont属性。也只有用老图标
        if (this.isDoc || !item.iconFont) {
          return `ico16 ${item.icon.split('.')[0]}_16`;
        }

        return `syDoc ${item.iconFont || 'defaultICON'}`;
      },
      /**
       * @description: 删除附件/关联文档
       * @param {String}fileUrl 当前删除项目用于在file那个对象上面删除的索引
       * @param {String}filename 当前删除项目名称
       * @param {Boolean}isUploading 当前删除项目是否为正在上传项目
       * @param {Function}cancel 正在上传项目取消上传
       * @param {Number}index 当前删除项目索引
       */
      deleteItem({ fileUrl, filename, isUploading, cancel }, index) {
        //如果是删除正在上传的临时文件（附件用）
        if (isUploading) {
          //取消上传
          cancel();
          //删除当前项
          this.$emit('deleteItem', index);
          let some = this.dataList.some(item => item.isUploading === true && item.process !== 100);
          if (!some) {
            useBaseInfo.attachmentUploading = false;
          }
          return;
        }
        //删除已上传文件
        this.$confirm({
          content: this.$i18n(
            this.isDoc ? 'assdoc.isdeletesomeone.mesg' : 'cap.template.common.text.Formsonprompt02',
            filename
          ),
          okText: this.$i18n('common.button.ok.label'),
          okType: 'danger',
          cancelText: this.$i18n('enum.cancel'),
          onOk: () => {
            //从界面移除
            this.$emit('deleteItem', index);
            if (this.isDoc) {
              //从回显用文件对象移除
              fileUploadAttachments.remove(createID(this.areaName, fileUrl));
            }
          },
        });
      },
      getFileSize(size, unit = 'K') {
        /*
         * 1024byte = 1K，1024K = 1M
         * 文件大小单位为 byte，先转化为 K，若超过 1024K，则再继续转化为 M。目前暂不考虑 G
         */
        if (!size && size !== 0) return;
        
        let fileSize = size / 1024;

        if (fileSize < 1024) {
          if (String(fileSize).indexOf('.') === -1) return `${fileSize}${unit}`; // 整除的情况下，直接返回

          fileSize = fileSize.toFixed(1); // 四舍五入保留1位小数
          const [intNum, decimalNum] = fileSize.split('.');

          if (decimalNum === '0') return `${intNum}${unit}`; // 'xxx.0'的情况下，应该返回整数部分

          return `${fileSize}${unit}`;
        }

        return this.getFileSize(fileSize, 'M');
      },
    },
  };
</script>
<style lang="scss" scoped>
  .accessory-item-container {
    > div {
      margin-right: 5px;
      margin-bottom: 8px;
      width: 50px;
      height: 23px;
      display: flex;
      align-items: center;

      > .data-length {
        margin-left: 5px;
        color: #999999;
        font-size: 12px;
      }

      > .batch-download {
        margin-left: 5px;
      }
    }

    > div.summary-container {
      width: 69px;
    }

    > ul {
      > li {
        position: relative;
        height: 23px;
        padding: 0 6px 0 4px;
        margin: 0 8px 8px 0;
        background-color: rgb(230, 238, 247);
        border-radius: 2px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        > section {
          display: flex;
          align-items: center;
        }

        > .left-item {
          font-size: 12px;

          > .syDoc {
            font-size: 16px;
          }

          > .name {
            @include ellipsis;
            max-width: 130px;
            margin: 0 5px;

            ::v-deep a {
              @include ellipsis;
              display: block;
            }
          }

          > .file-size {
            margin-left: -5px;
            margin-right: 5px;
          }
        }

        > .right-item {
          > .delete-icon {
            color: #8C8C8C;
          }

          > .ico16 {
            font-size: 16px;
            cursor: pointer;
          }
          
          > .progress-bg {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 1px;
            background-color: $primary-color;
            opacity: 0.5;
            transition: width $tn linear;
          }
        }

        &:hover {
          .file-handle-list {
            display: flex;
          }
        }
      }

      > li.item-wrapper {
        background: #F5F7FA;
        border-radius: 3px;
      }
    }

    > .list-container {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
    }
  }

  .accessory-item {
    display: flex;
    align-items: flex-start;
  }
</style>
